import { fileURLToPath } from "url";
import { dirname, join } from "path";//dirname函数用于获取文件路径中的目录部分;join函数用于将多个路径片段连接成一个完整的路径
import { createReadStream } from "fs";

import Koa from "koa";
import bodyParser from "koa-bodyparser";
import koaStatic from "koa-static";

import router from "./rooter/index.js";
import { errorHandler } from "./middleware/index.js";
const __filename = fileURLToPath(import.meta.url);//得到了当前正在执行的 JavaScript 文件的完整路径名
const __dirname = dirname(__filename);//获取文件路径中的目录部分
const app = new Koa();

process.on("uncaughtException", (err, origin) => {
  console.log(`Caught exception: ${err}\n` + `Exception origin: ${origin}`);
});

// 静态文件服务
app.use(koaStatic(join(__dirname, "../client/dist")));

//解析请求体
app.use(bodyParser());
app.use(errorHandler());
app.use(router.routes());

// 假如请求了一个不存在的方法，会返回 405，Method Not Allowed
app.use(router.allowedMethods())

// 添加一个中间件来处理所有非API路由
app.use(async (ctx, next) => {
  if (!ctx.path.startsWith('/api')) {
    try {
      // 尝试读取静态文件
      const filePath = join(__dirname, '../client/dist', ctx.path);
      try {
        await new Promise((resolve, reject) => {
          createReadStream(filePath)
            .on('error', reject)
            .on('end', resolve)
            .pipe(ctx.res);
        });
      } catch (err) {
        // 如果文件不存在，返回 index.html
        ctx.type = 'html';
        ctx.body = createReadStream(join(__dirname, '../client/dist/index.html'));
      }
    } catch (error) {
      console.error('Error serving file:', error);
      ctx.status = 500;
      ctx.body = 'Internal Server Error';
    }
  } else {
    await next();
  }
});

app.listen(8080, () => {
  console.log("The server is running on http://127.0.0.1:8080");
});
